package com.android.readcard.write;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;

import com.android.readcard.inter.ReadIccidListener;
import com.android.readcard.inter.WriteCardListener;
import com.android.readcard.utils.BleGlobUtils;
import com.android.readcard.utils.TextUtil;
import com.kaer.sdk.bt.BtReadClient;
import com.kaer.sdk.utils.CardCode;
import com.kaeridcard.client.BtReaderClient;
import com.kaeridcard.client.IClientCallBack;
import com.kaeridcard.client.IdCardItem;

import java.lang.reflect.Method;

/**
 * KT8003写卡
 */

public class Kt8003Write {
    private String blueAddress;
    private Activity mActivity;
    private ReadIccidListener mReadIccidListener;
    private WriteCardListener mWriteCardListener;
    private BtReadClient mBtReadClient;

    private BluetoothDevice mDevice;
    private BtReaderClient mClient;
    private int mType;

    public Kt8003Write(Activity context, String blueAddress, int mType, ReadIccidListener readIccidListener
            , WriteCardListener writeCardListener) {
        this.mActivity = context;
        this.blueAddress = blueAddress;
        this.mType = mType;
        this.mReadIccidListener = readIccidListener;
        this.mWriteCardListener = writeCardListener;
    }

    private boolean is_bt_connect = false;

    //******************************************读iccid************************************************
    public void connect() {
        mBtReadClient = BtReadClient.getInstance();
        mClient = new BtReaderClient(mActivity);
        if (mClient != null) {
            mClient.setCallBack(mCallback);
        }
        KaEr_WriteCard();//连接蓝牙
        KaEr_readICCIDTask(); //KT8003   读取iccid提交
    }

    /**
     * 断开连接
     */
    public void stopConnect() {
        if (mClient != null) {
            mClient.disconnectBt();
        }
        if (mBtReadClient != null) {
            mBtReadClient.disconnect();
            mBtReadClient.disconnectBt();
        }
        Log.e("项目异常Kt8003", "------Kt8003断开连接------" + "");
    }

    /**
     * kt8000的回调
     */
    private IClientCallBack mCallback = new IClientCallBack() {
        @Override
        public void onBtState(final boolean is_connect) {
            mActivity.runOnUiThread(new Runnable() {
                public void run() {
                    if (is_connect) {
//                        showToast("蓝牙已连接到");
                        Log.e("项目异常", "------蓝牙已连接------");
                    } else {
//                        showToast("蓝牙连接已断开");
                        Log.e("项目异常", "------蓝牙连接已断开------");
                    }
                    is_bt_connect = is_connect;
                }
            });
        }

        @Override
        public void onIddataHandle(IdCardItem idCardItem) {
        }
    };

    /**
     * 卡尔  蓝牙写卡器KT8003
     */
    private void KaEr_WriteCard() {
        try {
            //StrMac=(obj[whitch].split("\n")[1]);
            BluetoothAdapter adapte = BluetoothAdapter.getDefaultAdapter();
            mDevice = adapte.getRemoteDevice(blueAddress);
            boolean flag = mBtReadClient.connectBt(mDevice);
            //Toast.makeText(MainActivity.this, StrMac+"蓝牙数字123", 0).show();
            if (mDevice.getBondState() != BluetoothDevice.BOND_BONDED) {
                Method creMethod;
                try {
                    creMethod = BluetoothDevice.class.getMethod("createBond");
                    creMethod.invoke(mDevice);
                } catch (Exception e) {
                    mReadIccidListener.readIccidErr("请检查蓝牙是否配对");
                    e.printStackTrace();
                }
                return;
            }
            if (mBtReadClient.getBtState() == 2) {
                Log.e("项目异常", "------KT8003蓝牙已连接------" + "");
            } else {
                mReadIccidListener.readIccidErr("蓝牙未连接");
            }
        } catch (Exception e) {
            e.printStackTrace();
            mReadIccidListener.readIccidErr("连接超时,请重试.");
        }
    }

    /**
     * KT8003 读取ICCIDD
     */
    @SuppressLint("ShowToast")
    protected void KaEr_readICCIDTask() {
        // 读取ICCID
        String readICCIDResult = mBtReadClient.readICCID();
        if (TextUtils.isEmpty(readICCIDResult) || readICCIDResult.length() < 10) {
            mReadIccidListener.readIccidErr(CardCode.errorCodeDescription(Integer.parseInt(readICCIDResult)));
        } else {
            byte[] szCheckRes = new byte[1];
            byte[] szImsi2G = new byte[15];
            byte[] szImsiLen2G = new byte[1];
            byte[] szImsi3G = new byte[15];
            byte[] szImsiLen3G = new byte[1];
            int readIMSIResult = mBtReadClient.ReadIMSI((byte) 0x03, szCheckRes,
                    szImsi2G, szImsiLen2G, szImsi3G, szImsiLen3G);
            // 第一个参数 0x002表示读2G卡 0x03表示读3G 4G卡
            if (readIMSIResult != 1) {
                mReadIccidListener.readIccidErr("读取ICCID失败,请重新读卡!");
            } else {

                String imsi = TextUtil.bytesToASCString(szImsi3G);
                Log.e("项目异常", BleGlobUtils.isNum(imsi) + "------imsi------" + imsi);
                if (mType == 0) {
                    if (!BleGlobUtils.isNum(imsi)) {
                        mReadIccidListener.readIccidIsChengKa(1617,new String(readICCIDResult).trim(), "此卡是白卡,无需重置");
                    } else {
                        // 读iccid成功
                        mReadIccidListener.readIccidSuc(1, new String(readICCIDResult).trim(), imsi);
                    }
                } else {
                    if (BleGlobUtils.isNum(imsi)) {
                        mReadIccidListener.readIccidIsChengKa(1617,new String(readICCIDResult).trim(), "此卡是成卡,请换卡重试");
                    } else {
                        // 读iccid成功
                        mReadIccidListener.readIccidSuc(1, new String(readICCIDResult).trim(), imsi);
                    }
                }


            }
        }
    }
    //*************************************写卡*******************************************

    /**
     * 卡尔KT8003  写IMSI
     */
    public void writeIMSICardTask(final byte[] szImsi, final String sendNumber) {
        new AsyncTask<Integer, Integer, Integer>() {
            @Override
            protected Integer doInBackground(Integer... arg0) {
                return mBtReadClient.WriteIMSI(szImsi, szImsi);
            }

            @Override
            protected void onPostExecute(Integer result) {
                if (result == 1) {
                    WriteSMSCCardTask(sendNumber);
                } else {
                    // 写卡失败
                    mWriteCardListener.writeErr();
                    return;
                }
                super.onPostExecute(result);
            }
        }.execute();
    }

    /**
     * 卡尔KT8003  写Number
     */
    private void WriteSMSCCardTask(final String sendNumber) {
        final byte index = 1;// 短信中心号索引（每个sim卡可以有几个短信中心线性文件，从1开始）
        new AsyncTask<Integer, Integer, Integer>() {
            @Override
            protected Integer doInBackground(Integer... arg0) {
                return mBtReadClient.WriteSMSC(sendNumber, index);
            }

            @Override
            protected void onPostExecute(Integer result) {
                if (result == 1) {
                    mWriteCardListener.writeSuc();
                } else {
                    // 写卡失败
                    mWriteCardListener.writeErr();
                    return;
                }
                super.onPostExecute(result);
            }
        }.execute();
    }
}
